<?php
namespace control;
// 采购合同
class purchaseContractClass extends adIndexClass
{
	private const page        = 'purchaseContract';                 # 权限
	private const table       = 'purchase_contract';                # 数据表
	private const tablePay    = 'sales_contract_payback';           # 回款表
	private const tableMx     = 'purchase_contract_detail';         //销售合同明细表
	private const title       = '采购合同';
	private const stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'contractTrackSearch':
                $tr = [
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'contract'  => [
                        'name'  => "合同编号",
                        'width' => 200,
                    ],
                    'orderType'         => [
                        'name'  => '业务类别',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'supplier'         => [
                        'name'  => '供应商',
                        'width' => 200,
                    ],
                    'code'         => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '物料名称',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'model'         => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'         => [
                        'name'  => '单位',
                        'width' => 70,
                    ],
                    'num'         => [
                        'name'  => '收货数量',
                        'width' => 100,
                    ],
                    'price'          => [
                        'name'  => '单价（' . static::$unit . '）',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '金额（' . static::$unit . '）',
                        'width' => 100,
                    ],
                    'rate'          => [
                        'name'  => '税率(%)',
                        'width' => 100,
                    ],
                    'taxMoney'          => [
                        'name'  => '税额（' . static::$unit . '）',
                        'width' => 100,
                    ],
                    'moneyWithTax'          => [
                        'name'  => '价税合计（' . static::$unit . '）',
                        'width' => 150,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 200,
                    ]
                ];
                break;
            case 'supplierContractSearch':
                $tr = [
                    'signedDate'          => [
                        'name'  => '签订日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "合同编号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => "合同名称",
                        'width' => 300,
                    ],
                    'type'         => [
                        'name'  => '合同类别',
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => '合同金额（' . static::$unit . '）',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
                break;
            default:
                $tr = [
                    'signedDate'          => [
                        'name'  => '签订日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "合同编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => "合同名称",
                        'width' => 300,
                    ],
                    'supplier'         => [
                        'name'  => '供应商名称',
                        'width' => 200,
                    ],
                    'type'          => [
                        'name'  => '合同类别',
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => '合同金额（' . static::$unit . '）',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function supplierContractOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "签订日期" => text(['name' => 'signedDate', 'laydate' => ['range' => '~', 'type' => 'date'],]).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    "合同编号"   => text(["name" => "orderNo"]),
                    '合同名称' => text(["name" => "name"]),
                ],
                [
                    "合同类别" => select(["name" => "type", 'option' => ['主合同', '补充协议']]),
                    '状态' => select(["name" => "state", 'option' => self::stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 供应商页卡
	 *
	 * @return bool|string
	 */
	public function supplierContract(): bool|string
	{
        $html = $this->supplierContractOptions(false);
        $button = "";
		//返回
		$json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
		return json_encode($json, 320);
	}

	public function supplierContractSearch(): bool|string
	{
		$targetId = $this->post('targetId');
		//like查询数组
		$equal = [
			'type'  => $this->post('type'),
			'state' => $this->post('state'),
			'coid'  => self::$coid,
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
			'name'    => $this->post('name'),
		];
		$and   = " and supplierId = '$targetId'";
		if ($this->post('signedDate')) {
			$and .= self::timeComparison($this->post('signedDate'), 'date', 'signedDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//生成查询语句
		$where = search([
				"="    => $equal,
				"like" => $like,
			]) . $and;
		$page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=detail&id=' . $array['id'] . "')"],
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "money":
                        $row[] = self::lostZero($array['money'], 'amount');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='invoiceForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "签订日期" => text(['name' => 'signedDate', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                    "合同编号"   => text(["name" => "orderNo"]),
                    '合同名称' => text(["name" => "name"]),
                ],
                [
                    '供应商'  => supplierClass::supplierSelect(array('title' => '')),
                    "合同类别" => select(["name" => "type", 'option' => ['主合同', '补充协议']]),
                    '状态' => select(["name" => "state", 'option' => self::stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*入口页*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url      = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=editPage')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= spanButton(['name' => '删除', 'page' => self::page, 'fun' => 'operate', 'para' => ['act' => 'del'], 'first' => true]);
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*合同列表*/
	public function homeSearch()
	{
		//查询结果
		$where = ' 1=1 ';
		$equal = [
			'supplierId' => $this->post('supplierId'),
			'type'       => $this->post('type'),
			'state'      => $this->post('state'),
			'coid'       => self::$coid,
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
			'name'    => $this->post('name'),
		];
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('signedDate')) {
			$where .= self::timeComparison($this->post('signedDate'), 'date', 'signedDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page                          = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
		$_SESSION[self::page]['where'] = $where;
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		$url      = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = [
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => ["title" => "采购合同详情", "click" => "newIframe('销售合同详情','" . root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=detail&id=' . $array['id'] . "')"],
				"edit"   => $array['state'] == '草稿' ? ["title" => "采购合同编辑", "click" => "newIframe('采购合同编辑','" . root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $array['id'] . "')"] : [],
			];
			if ($array['state'] == '已通过') {
				unset($dominate['edit']);
			}
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $supplier = query('supplier', "id = '$array[supplierId]'");
                        $row[] = $supplier['name'];
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money'], 'amount');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalMoney = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'      => self::lostZero($totalMoney['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 审核按钮
	 *
	 * @param $info
	 * @return array
	 */
	public function auditButton($info): array
	{
		if (empty($info['id'])) {
			return [];
		}
		$button = [];
		if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
			$button[] = [
				"name"  => '提交审批',
				"type"  => "弹出层",
				"cla"   => 'audit',
				"fun"   => "operate",
				'style' => 'li-btn-blue-bg',
				"post"  => [
					"act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'name'    => self::title,
						'table'   => self::table,
						'process' => [
							// 预览函数
							'detail' => [
								'cla' => $this->get('cla'),
								'fun' => 'detail',
							],
							// 保存函数
							'save'   => [
								'cla' => $this->get('cla'),
								'fun' => 'editPageEdit',
							],
							//执行发起时验证函数
							'before' => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
							//完成发起后执行函数
							'after'  => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
						],
					], 320)),
				],
			];
		}
		// 审批并判断是否有权限
		if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
			$button[] = [
				"name"  => '审批',
				"type"  => "弹出层",
				"cla"   => 'audit',
				"fun"   => "operate",
				// 以下参数固定格式
				"post"  => [
					"act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table'   => self::table,
						// 当前状态
						'state'   => $info['state'],
						// 变更
						'field'   => ['state'],   //变更字段 可多个
						'value'   => [
							'state' => ['草稿', '已通过'],
						],
						// 审核时回调
						'process' => [
							//执行首次审核时验证
							'before' => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
							//执行末次审核后处理
							'after'  => [
								'cla'  => $this->get('cla'),
								'fun'  => 'useDone',
								'data' => ['id' => $info['id']],
							],
						],
					], 320)),
				],
				'style' => 'li-btn-blue-bg',
			];
			$button[] = [
				"name" => '添加审批人',
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table' => self::table,
					], 320)),
				],
			];
			$button[] = [
				"name" => '转交',
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table' => self::table,
					], 320)),
				],
			];
		}
		// 撤销审批
		if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
			$button[] = [
				"name" => '撤销审批',
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table'   => self::table,
						// 当前状态
						'state'   => $info['state'],
						// 变更
						'field'   => ['state'],   //变更字段 可多个
						'value'   => [
							'state' => ['草稿'],
						],
						'process' => [
							//完成发起后执行函数
							'after' => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
						],
					], 320)),
				],
			];
		}
		return $button;
	}


	public function editPage()
	{
	    $id = $this->get('id')?:suiji();
		$info = query(self::table, " id = '" . $id . "' ");
		//按钮
		$button[]  = [
			"name"  => "保存",
			"type"  => "点击事件",
			"cla"   => $this->get('cla'),
			"fun"   => "subForm('" . self::page . "EditPageForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
			"post"  => ["id" => $this->get('id')],
			'style' => 'li-btn-blue-bg',
		];
        $button[] = [
            "name" => '保存并提交',
            "type" => "弹出层",
            "cla" => $this->get('cla'),
            "fun" => "saveAndCommit",
            "post" => "$('[name=" . self::page . "EditPageForm]').serialize()+'&act=start'",
        ];
		$type      = 'payback';
		$moneyTr[] = ['', '计划付款日期', '计划付款金额（' . static::$unit . '）', '阶段', '备注'];
        $result = find(array(
            'field' => "id,date,money,stage,text",
            'table' => self::tablePay." where orderId = '{$info['id']}' order by time DESC"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['money'] = $array['money'] ? self::lostZero($array['money'], 'amount') : '';
                $array = (new salesContractClass())->prefixArrayKeys($array,$type);
                $array['list'] = $k+1;
                $moneyTr[] = $this->paybackRow($array);
            }
        }else{
            $moneyTr[] = $this->paybackRow([$type.'id'=>self::getId(), 'list'=>1]);
        }
        $info['orderNo']      = $info['orderNo']?:codeTemplateClass::generateCode(self::page, [
            'prefix' => 'CG' . date('Ymd'),
            'table'  => self::table,
            'field'  => 'orderNo',
            'where'  => " AND coid = '" . self::$coid . "' ",
        ], []);
		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '合同编号' => text(['name' => "orderNo", 'class' => 'text', 'value' => $info['orderNo']]),
                    must . '合同名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
                    must . '供应商'   =>
                        supplierClass::supplierSelect(array('value'=>$this->get('supplierId') ?: $info['supplierId'],'param'=>"{type:'启用'}")),
                    //selectMultiple(['table' => 'supplier', "title" => '请选择', 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'supplierId', 'value' => $this->get('supplierId') ?: $info['supplierId'], 'class' => 'width250']),
                    must . '合同类别' => radio(['name' => "type", 'class' => 'text', 'checked' => $info['type'] ?: '主合同', 'value' => ['主合同', '补充协议']]),
                ],
                [
                    must . '签订日期' => text(['name' => "signedDate", 'class' => 'text', 'value' => $info['signedDate'], 'laydate' => [],]),
                    '有效开始日期'    => text(['name' => "startDate", 'class' => 'text', 'value' => $info['startDate'], 'laydate' => [],]),
                    '有效结束日期' => text(['name' => "endDate", 'class' => 'text', 'value' => $info['endDate'], 'laydate' => [],]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ],
            '金额信息' => [
                [
                    must . '合同金额：' => text(['name' => "money", 'other' => self::digitalFiltering(), 'unit' =>  static::$unit , 'value' => self::lostZero($info['money'])]),
                    '结算方式：'        => radio(['name' => "settleType", 'class' => 'text', 'checked' => $info['settleType'], 'value' => ['预付', '现付', '月结'],]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'html' => $this->listTable(['tr' => $moneyTr, 'end' => true]),
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
		]);
		$data['html'] .= <<<EOT
        <script>
            //添加一行
            function addRow(e,type){
                $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{type:type},function (res){
                    $(e).closest('tr').after(res.data);
                    resetNumber($(e).closest('tbody'))
                },'json');
            }
        </script>
EOT;

		//返回
		return $this->tab($data);
	}

    /**
     * Desc : 回款计划明细
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function paybackRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $type = 'payback';
        $id = isset($data[$type.'id'])&&$data[$type.'id']?$data[$type.'id']:self::getId();
        $field = [$type.'date', $type.'money', $type.'stage', $type.'text'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'paybackRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this,'$type')"),
            hidden(['name' => $type . 'id[]', 'value' => $id]) .
            text(['name' => $type . 'date[]', 'laydate' => [], 'title' => '计划付款日期', 'value' => $array[$type.'date']]),
            text(['name' => $type . 'money[]', 'type' => 'text', 'other' => self::digitalFiltering(), 'title' => '计划付款金额（' . static::$unit . '）', 'value' => $array[$type.'money']]),
            select(['name' => $type . 'stage[]', 'title' => '阶段', 'option' => explode('，', para('salesContractStageOption')), 'value' => $array[$type.'stage']]),
            textarea(['name' => $type . 'text[]', 'title' => '备注', 'value' => $array[$type.'text']]),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

	/**
	 *添加一行
	 */
	public function addRow()
	{
		$type = $this->post('type');
		$html = '';
		switch ($type) {
			case 'payback':
                $res = json_decode($this->paybackRow(),true);
                $html = $res['html'];
				break;
		}
		$json['data'] = $html;
		return json_encode($json, 320);
	}

	/*基本资料新增或修改-异步处理*/
	public function editPageEdit()
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'orderNo'    => $this->post('orderNo'),
			'name'       => $this->post('name'),
			'supplierId' => $this->post('supplierId'),
			'type'       => $this->post('type'),
			'signedDate' => $this->post('signedDate'),
			'startDate'  => $this->post('startDate'),
			'endDate'    => $this->post('endDate'),
			'money'      => $this->post('money') ? self::formattingFigure($this->post('money')) : '',
			'settleType' => $this->post('settleType'),
			'text'       => $this->post('text'),
		];
		$annotation = [
			'orderNo'    => '合同编号',
			'name'       => '合同名称',
			'supplierId' => '供应商',
			'type'       => '类型',
			'signedDate' => '签订日期',
			'money'      => '合同金额',
		];
		$rules      = [
			'orderNo'    => 'required',
			'name'       => 'required',
			'supplierId' => 'required',
			'type'       => 'required',
			'signedDate' => 'required',
			'money'      => 'required|numeric',
		];
        // 合同回款
        $type = 'payback';
        $paybackField = [
            'id' => $this->post($type . 'id'),
            'coid' => self::$coid,
            'orderId' => $id,
            'date' => $this->post($type . 'date'),
            'money' => $this->post($type . 'money'),
            'stage' => $this->post($type . 'stage'),
            'text' => $this->post($type . 'text'),
            'time' => $this->time,
        ];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::total(array('table' => self::table, 'where' => "id !='$id' and coid = '" . self::$coid . "' and orderNo = '$field[orderNo]'")) > 0) {
			$json['warn'] = '已存在此合同编号';
		} elseif (!empty($field['startDate']) && !empty($field['endDate']) && strtotime($field['endDate']) < strtotime($field['startDate'])) {
			$json['warn'] = '结束日期不能小于开始日期';
		} else {
			$this->startTrans();
			$where = " id = '$id' ";
			$info  = query(self::table, $where);
			if (!$info['id']) {
				$field        = array_merge($field, [
					'id'      => $id,
					'coid'    => self::$coid,
					'manager' => $this->control['stid'],
					'state'   => '草稿',
					'stid'    => $this->control['stid'],
					'time'    => $this->time,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}

			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                if (is_array($paybackField)) {
                    $checkPaybackKey = ['date','money','stage','text'];
                    static::insertArray(self::tablePay, $paybackField, emptyFilter: $checkPaybackKey);
                    if (!empty(current($paybackField))) {
                        delete(['table' => self::tablePay, 'where' => " id NOT IN ('" . implode("','", current($paybackField)) . "') AND orderId = '$id'  "]);
                    }
                }
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】' . ($field['name'] ? "，合同名称【{$field['name']}】" : '');
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                $json['id'] = $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}

    /**
     * 保存并提交审批
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editPageEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            $id = $result['id'];
            $body = self::encryptDecrypt(json_encode([
                'name'    => self::title,
                'table'   => self::table,
                'process' => [
                    // 预览函数
                    'detail' => [
                        'cla' => $this->get('cla'),
                        'fun' => 'detail',
                    ],
                    // 保存函数
                    'save'   => [
                        'cla' => $this->get('cla'),
                        'fun' => 'editPageEdit',
                    ],
                    //执行发起时验证函数
                    'before' => [
                        'cla' => $this->get('cla'),
                        'fun' => '',
                    ],
                    //完成发起后执行函数
                    'after'  => [
                        'cla' => $this->get('cla'),
                        'fun' => '',
                    ],
                ],
                'href' => isset($result['href'])?$result['href']:'',
            ], 320));
            $res = auditClass::submitApprovalSignle($id,$body);
            if($res['warn'] == 1){
                return $res['data']; //自定义审批人
            }elseif($res['warn'] != 2){
                $_SESSION['warn'] = '提交失败，'.$res['warn'];
            }
        }
        return $resultJson;
    }


	/**
	 * 详情页
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " id = '" . $this->get('id') . "' ");
		if (!$this->power(self::page, "see")) {
			$html = "你没有查看权限";
		} elseif (!$this->get('id')) {
			$html = "ID为空";
		} elseif (!$info['id']) {
			$html = "未找到此信息";
		} else {
			$data = [
				"id"   => $info['id'],
				"menu" => [
					"detail"        => "基本信息",
					"contractMx"    => "合同明细",
					'contractTrack' => '合同跟踪',
					"file"          => ["name" => "附件", "cla" => "file", "fun" => "purchaseContractFile"],
				],
			];
			//按钮
			$button = [];
			if ($info['state'] == '草稿') {
				if ($this->power(self::page, "del")) {
					$button[] = [
						"name" => "删除",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'del', "id" => $info['id']],
					];
				}
				if ($this->power(self::page, "edit")) {
					$button[] = [
						"name"  => "编辑",
						"type"  => "顶部页卡",
						"title" => "编辑用户",
						"url"   => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $info['id'],
					];
				}
			}
			// 金额信息
			$moneyTr[] = ['计划付款日期', '计划付款金额（' . static::$unit . '）', '阶段', '备注'];
			$result    = find(['table' => self::tablePay . " where orderId = '{$info['id']}' order by list"]);
			foreach ((array)$result['array'] as $array) {
				$moneyTr[] = [self::formatDate($array['date']), self::lostZero($array['money']), $array['stage'], $array['text']];
			}
			$moneyTab = $this->listTable(["tr" => $moneyTr, 'showSort' => true]);
			$supplier = query('supplier', "id = '$info[supplierId]'");
			//审核按钮
			$button = array_merge($button, $this->auditButton($info));
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				"基本信息" => [
					[
						"合同编号"   => $info['orderNo'],
						"合同名称"   => $info['name'],
						"供应商名称" => $supplier['name'],
						"销售员"   => self::findStaff($info['manager']),
					],
					[
                        "合同类别" => $info['type'],
                        "签订日期" => self::formatDate($info['signedDate']),
						"有效开始日期" => self::formatDate($info['startDate']),
						"有效结束日期" => self::formatDate($info['endDate']),
					],
					[
						"备注" => pre($info['text']),
					],
				],
				"金额信息" => [
					[
						"合同金额(". static::$unit . ")" => self::lostZero($info['money']),
						"结算方式"               => $info['settleType'],
					],
				],
			]);
            $data['html'] .= $this->detailList([
                'html' => $moneyTab,
            ]);
            $data['html']   .= $this->tableShow([
                "系统信息" => [
                    [
                        "创建人"   => self::findStaff($info['stid']),
                        "创建时间" => self::formatDate($info['time']),
                        "更新时间" => self::null($info['updateTime']),
                    ],
                ],
                "流程"     => [
                    [
                        auditClass::auditRecord(self::table, $info['id']),
                    ],
                ],
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

    /*列表页-查询条件*/
    public function contractTrackOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "单据编号"   => text(array("name" => "orderNo")),
                    '供应商' => selectMultiple(["name" => "supplierId", 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name']),
                ],
                [
                    "物料名称" => text(["name" => "name"]),
                    "物料编码" => text(["name" => "code"]).
                        hidden(["name" => "orderId", 'value' => $this->get('id')]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 合同跟踪
	 */
	public function contractTrack(): bool|string
	{
        $html = $this->contractTrackOptions(false);
        $button = "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
	}

	/**
	 * 合同跟踪
	 */
	public function contractTrackSearch(): bool|string
	{
		$id   = $this->post('orderId');
		$info = query(self::table, " id = '$id' ");
		//查询结果
		$where = " main.contractId = '$id'  ";
		//生成查询语句
		$where .= search([
			"like" => [
				'code'    => $this->post('code'),
				'name'    => $this->post('name'),
				'orderNo' => $this->post('orderNo'),
			],
			"="    => [
				'main.supplierId' => $this->post('supplierId'),
				"main.state"      => '已确认',
			],
		]);
		if ($this->post('createTime')) {
			$where .= self::timeComparison($this->post('createTime'), 'date', 'main.recordDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'a.list',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
		$page                        = $this->page([
			"table" => "purchase_order as main join purchase_order_detail as a on main.id = a.orderId join material as b on a.materialId = b.id",
			'field' => "b.*,main.contractId,main.isTax,a.id as mxId,a.orderId,a.id,a.price,a.num,a.money,a.rate,a.text,main.recordDate,main.orderNo,main.type as orderType,main.supplierId",
			"where" => $where,
			"order" => $orderBy['orderBy']
		]);
		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
		//获取记录
		foreach ($page['array'] as $array) {
			$num      = find(array(
			    'table' => 'purchase_get_order as a join purchase_get_order_detail as b on a.id = b.orderId',
                'field' => "ifnull(sum(b.num),0) as num",
                'single' => "sourceId = '$array[mxId]' and state = '已确认'"
            ))['num'];
			$result   = saleOrderClass::isTax($num, $array['price'], $array['rate'], $array['isTax']);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "contract":
                        $contract = query('purchase_contract', "id = '$array[contractId]'");
                        $row[] = $contract['orderNo'];
                        break;
                    case "supplier":
                        $supplier = query('supplier', "id = '$array[supplierId]'");
                        $row[] = $supplier['name'];
                        break;
                    case "num":
                        $row[] = self::lostZero($num, 'numPrecision');
                        break;
                    case "price":
                        $row[] = self::lostZero($array['price'], 'pricePrecision');
                        break;
                    case "rate":
                        $rate     = ($array['rate'] * 100) . '%';
                        $row[] = $rate;
                        break;
                    case "money":
                    case "taxMoney":
                    case "moneyWithTax":
                        $row[] = self::lostZero($result[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
		//控件
		$json['html'] = $page['hint'] . $button . "<form name='mxForm'>" . $li . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 导出
	 */
	public function exportData()
	{
		$tr     = [];
		$sql    = $_SESSION[self::page]['sql'];
		$title  = array('单据日期', '单据编号', '合同编号', '业务类别', '供应商', '物料编码', '物料名称', '规格型号', '单位', '收货数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '税率(%)', '税额（' . static::$unit . '）', '价税合计（' . static::$unit . '）', '备注');
		$result = sqlFind($sql);
		if (is_array($result)) {
			foreach ($result as $array) {
				$num      = find(array(
				    'table' => 'purchase_get_order as a join purchase_get_order_detail as b on a.id = b.orderId',
                    'field' => "ifnull(sum(b.num),0) as num",
                    'single' => "sourceId = '$array[mxId]' and state = '已确认'"
                ))['num'];
				$rate     = ($array['rate'] * 100) . '%';
				$supplier = query('supplier', "id = '$array[supplierId]'");
				$result   = saleOrderClass::isTax($num, $array['price'], $array['rate'], $array['isTax']);
				$contract = query('purchase_contract', "id = '$array[contractId]'");
				$tr[]     = [
					$array['recordDate'],
					$array['orderNo'],
					$contract['orderNo'],
					$array['orderType'],
					$supplier['name'],
					$array['code'],
					$array['name'],
					$array['model'],
					$array['unit'],
					self::lostZero($num, 'numPrecision'),
					self::lostZero($array['price'], 'pricePrecision'),
					self::lostZero($result['money']),
					$rate,
					self::lostZero($result['taxMoney']),
					self::lostZero($result['moneyWithTax']),
					$array['text'],
				];
			}
		}
		$text = $this->control['name'] . "导出了采购合同跟踪表";
		$this->logText(["type" => self::page, "text" => $text]);
		$this->excelOut($title, $tr, "采购合同跟踪表.xlsx");
		header("Location:" . getenv("HTTP_REFERER"));
		exit(0);
	}

    /*列表页-查询条件*/
    public function contractMxOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "物料编码" => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "name")),
                    "规格型号"   => text(array("name" => "model")).
                        hidden(["name" => "orderId", 'value' => $this->get('id')?$this->get('id'):$this->post('id')]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 合同明细
	 *
	 * @return bool|string
	 */
	public function contractMx()
	{
        $html = $this->contractMxOptions(false);
        $info = query(self::table, " id = '".$this->get('id')."' ");
        $button = '';
        if ($info['state'] == '草稿') {
            $button .= spanButton(['name' => '选择产品', 'page' => '' . $this->get('cla') . '', 'fun' => 'addMx', 'para' => ['id' => self::getId(), 'orderId' => $info['id'], 'callback' => self::page, 'tableMx' => self::tableMx], 'first' => true]);
        }
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button, searchOption: "{id:'".$this->get('id')."'}");
        return json_encode($json, 320);
	}

	/**
	 *  合同明细
	 *
	 * @return bool|string
	 */
	public function contractMxSearch()
	{
		$id   = $this->post('orderId');
		$info = query(self::table, " id = '$id' ");
		//查询结果
		$where = " orderId = '$id'   ";
		//生成查询语句
		$where .= search([
			"like" => [
				'code'  => $this->post('code'),
				'name'  => $this->post('name'),
				'model' => $this->post('model'),
			],
		]);
		$page  = $this->page([
			"table" => self::tableMx . " as a join material as b on a.materialId = b.id",
			'field' => "b.*,a.orderId,a.materialId,a.id,a.price,a.num,a.money,a.taxMoney,a.moneyWithOutTax,a.num,a.unit,a.rate,a.text",
			"where" => $where,
			"order" => "a.list desc",
		]);

		//获取表头
		$tr[] = ['', '物料编码', '物料名称', '规格型号', '单位', '采购批量', '单价（' . static::$unit . '）', '未税金额（' . static::$unit . '）', '税率(%)', '税额（' . static::$unit . '）', '价税合计（' . static::$unit . '）', '备注'];
		//获取记录
		foreach ($page['array'] as $k=>$array) {
			if ($info['state'] == '草稿') {
				$num   = text(['name' => 'num', 'other' => self::digitalFiltering('numPrecision'), 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'class' => 'text width100', 'value' => self::lostZero($array['num'], 'numPrecision'), 'blur' => "textUpdate, {$this->get('cla')}, updateMx", 'title' => '数量']);
				$price = text(['name' => 'price', 'other' => self::digitalFiltering('pricePrecision'), 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'class' => 'text width100', 'value' => self::lostZero($array['price'], 'pricePrecision'), 'blur' => "textUpdate, {$this->get('cla')}, updateMx", 'title' => '价格']);
				$rate  = select(['name' => 'rate', 'value' => $array['rate'] * 100, 'title' => '税率', 'class' => 'select width100', 'option' => explode('，', para('taxRate')), 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'change' => "textUpdate, {$this->get('cla')}, updateMx",]);
				$total = text(array('name' => 'money', 'type' => 'text', 'other' => self::digitalFiltering('amount'), 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'blur' => "calculatePrice(this);textUpdate, {$this->get('cla')}, updateMx", 'class' => 'text width100', 'value' => self::lostZero($array['money'])));
				$unit  = select(array('name' => 'unit', 'value' => $array['unit'], 'class' => 'select width100', 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'title' => '单位', 'change' => "textUpdate, {$this->get('cla')}, updateMx", 'option' => machiningOrderClass::unitOption($array['materialId'])));
				$text  = text(['name' => 'text', 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'class' => 'text width200', 'value' => $array['text'], 'blur' => "textUpdate, {$this->get('cla')}, updateMx", 'title' => '备注']);
			} else {
				$num   = self::lostZero($array['num'], 'numPrecision');
				$price = self::lostZero($array['price'], 'pricePrecision');
				$rate  = ($array['rate'] * 100) . '%';
				$text  = $array['text'];
				$total = self::formattingFigure($array['money']);
				$unit  = $array['unit'];
			}

            $list = ((int)$page['para']['pageNow'] - 1) * (int)$page['para']['pageNum'] + $k + 1;
            $operate = "<span class='list-number'>{$list}</span>";
            $operate .= $info['state'] == '草稿' ? "<div class='delete-ico' onclick=\"layer('" . self::page . "','deleteMx',{id:'" . $array['id'] . "',orderId:'" . $array['orderId'] . "'})\"></div>" : '';
			$rateTotal = self::formattingFigure($array['taxMoney']);
			$tr[]      = [
                "<div class='list-edit-toolbar'>$operate</div>",
				$array['code'],
				$array['name'],
				$array['model'],
				$unit,
				$num,
				$price,
				"<span class='noTaxMoney'>" . self::lostZero($array['moneyWithOutTax']) . "</span>",
				$rate,
				"<span class='taxMoney'>{$rateTotal}</span>",
				$total,
				$text,
			];
		}
		//控件
		$json['html'] = "<form name='contractMxForm'>" . $this->tableMany(array("tr" => $tr, "page" => $page['para'])) . "</form>" . self::updateJs() . $page['button'];
		return json_encode($json, 320);
	}

    public static function updateJs()
    {
        return <<<eof
<script>
//通过单价计算金额，税额等
function countMoney(e){
    let trObj = $(e).parent().parent();
    countProcess(trObj)
}
function countProcess(trObj){
    let price = trObj.find("[name='price']").val();
    let num = trObj.find("[name='num']").val();
    let rate = trObj.find("[name='rate']").val();
    rate = Number(rate)/100;
    let money;
    let taxMoney,moneyWithTax;
    if($("[name='isTax']").is(":checked")){
       //含税单价
       taxMoney = (Number(price)*Number(num)/(1+rate)*rate).toFixed(amountPrecision);
       moneyWithTax = (Number(price)*Number(num)).toFixed(amountPrecision);
       money = Number(moneyWithTax-taxMoney).toFixed(amountPrecision)
    }else{
       //未含税单价
        taxMoney = (Number(price)*Number(num)*rate).toFixed(amountPrecision);
        moneyWithTax = (Number(price)*Number(num)*(1+rate)).toFixed(amountPrecision);
        money = (Number(price)*Number(num)).toFixed(amountPrecision);
    }
    trObj.find(".noTaxMoney").html(moneyWithTax)
    trObj.find(".taxMoney").html(taxMoney)
    trObj.find("[name='money']").val(money)
}
//通过价税合计计算单价
function calculatePrice(e){
    let trObj = $(e).parent().parent();
    let moneyWithTax = e.value;//价税合计
    let num = trObj.find("[name='num']").val();
    let rate = trObj.find("[name='rate']").val();
    if(num > 0){
        rate = Number(rate)/100;
        let taxMoney,price,money;
        taxMoney = (moneyWithTax/(1+rate)*rate);//税额
        if($("[name='isTax']").is(":checked")){
           //含税
           price = moneyWithTax/num;
           money = moneyWithTax-taxMoney;
        }else{
           //未含税
            price = (moneyWithTax-taxMoney)/num;
            money = moneyWithTax-taxMoney;
        }
        
        trObj.find(".noTaxMoney").html(money.toFixed(amountPrecision))
        trObj.find(".taxMoney").html(taxMoney.toFixed(amountPrecision))
        trObj.find("[name='price']").val(price.toFixed(amountPrecision))
    }
}

// 单个文本框更新
function textUpdate(obj, cla, fun) {
    let field = $(obj).attr('name'), val = $(obj).val()
    if (field.length > 0 && val.length > 0) {
        const url = root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun
        let params = {}
        // 判断是否有data-* 参数
        if ($(obj).data()) {
            Object.assign(params, $(obj).data())
            params[field] = val
        }
        $.post(url, params, function (resp) {
            if (resp.warn === 2) {
                if (field !=='money'){
                      countMoney(obj)
                }
                if (resp.href) {
                    window.location.href = resp.href;
                } else {
                    msg(resp.msg)
                }
            } else {
                warn(resp.warn)
            }
        }, "json");
    }
}
//切换含税不含税复选框
function taxChange(id){
    let isTax = $("[name='isTax']").is(":checked") ? 1 : 0
    $.post(root+'control/adIndex.html?cla=salesContract&fun=taxChange',{id: id,isTax: isTax},function(res) {
        $("[name='contractMxForm'] [name='price']").each(function() {
           textUpdate($(this),'salesContract','updateMx')
        })
    },'json');
}
</script>
eof;
    }


    /**
	 * 添加产品
	 *
	 * @return bool|string
	 */
	public function addMx()
	{
        $id    = $this->post('orderId');
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 0;
        $data             = [
            'sub'            => " onclick=\"subForm('mxForm', '" . root . "control/adIndex.html?cla=" . self::page . "&fun=addMxEdit');\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(["name" => "id", "value" => $id]) .
                hidden(["name" => "source", "value" => '采购']) .
                hidden(["name" => "attach", "value" => base64_encode(" and id not in (select materialId from " . self::tableMx . " where orderId = '$id') ")]),
        ];
        return $materialClassObj->addMx($data);
	}


	/**
	 * 编辑
	 * 添加
	 *
	 * @return bool|string
	 */
	public function addMxEdit()
	{
		$id      = $this->post('id');
		$mxIdArr = $this->post('mxId');
		$info    = query(self::table, " id = '{$id}'");
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = '请选择物料';
		} else {
			$x    = 0;
			$text = '';
			foreach ($mxIdArr as $mxId) {
				$material    = query('material', " id = '$mxId'");
				$mxWhere     = " materialId = '$mxId' and orderId = '$id'";
				$mx          = query(self::tableMx, $mxWhere);
				if (empty($mx['id'])) {
					//未在明细中
					$warn = insert([
						'table' => self::tableMx,
						'field' => [
							'id'            => self::getId(),
							'coid'          => self::$coid,
							'orderId'       => $id,
							'unit'          => $material['unit'],
							'materialId'    => $material['id'],
							'time'          => $this->time,
						],
					]);
					if (in_array($warn, ['新增成功', '更新成功'])) {
						$x++;
						$text .= $this->control['name'] . "添加了物料【{$material['name']}】到" . self::title . "【{$info['orderNo']}】中成功<br>";
					}
				} else {
					$text .= $this->control['name'] . "添加了物料【{$material['name']}】失败：已存在此物料<br>";
				}
			}
			$this->logText(["type" => self::page, "text" => $text]);
			$json['warn']     = 2;
			$json['href']     = $this->root . "control/adIndex.html?cla=" . self::page . "&fun=detail&menu=contractMx&id=" . $id;
			$_SESSION['warn'] = '添加了' . $x . '个物料到' . self::title;
		}
		return json_encode($json, 320);
	}

	public function deleteMx()
	{
		// 条件字段
		$wField = [
			'id'      => $this->post('id'),
			'orderId' => $this->post('orderId'),
		];
		$info   = query(self::table, " id = '{$wField['orderId']}' ");
		$state  = '草稿';
		if ($info['state'] != $state) {
			$json['warn'] = self::title . '申请单非' . $state . '状态，无法删除';
		} else {
			$warn         = delete([
				'table' => self::tableMx,
				'where' => generateWhere($wField),
			]);
			$json['warn'] = ($warn == '删除成功') ? 2 : $warn;
			$json['href'] = root . 'control/adIndex.html?cla=purchaseContract&fun=detail&id=' . $wField['orderId'] . '&menu=contractMx';
		}
		return json_encode($json, 320);
	}

	/**
	 * 更新
	 *
	 * @return bool|string
	 */
	public function updateMx()
	{
		// 条件字段
		$wField = [
			'id'      => $this->post('id'),
			'orderId' => $this->post('orderid'),
		];
		// 更新字段
		$field = [
			'unit'  => $this->post('unit'),
			'num'   => $this->post('num') ? self::formattingFigure($this->post('num'), 'numPrecision') :'',
			'price' => $this->post('price') ? self::formattingFigure($this->post('price'), 'pricePrecision') : '',
			'rate'  => $this->post('rate') ? (float)$this->post('rate') / 100 : '',
			'text'  => $this->post('text'),
		];
		$info  = query(self::table, " id = '{$wField['orderId']}' ");
		$state = '草稿';
		if ($info['state'] != $state) {
			$json['warn'] = self::title . '申请单非' . $state . '状态，无法修改';
		} else {
			$mx    = query(self::tableMx, "id = '" . $this->post('id') . "'");
			$where = generateWhere($wField);
			if ($field['num'] || $field['price'] || $field['rate'] || $this->post('money')) {
				if ($this->post('money')) {
					$taxMoney       = self::formattingFigure($this->post('money') / (1 + $mx['rate']) * $mx['rate']);//税额
					$field['price'] = self::formattingFigure(($this->post('money') - $taxMoney) / $mx['num']);
				}
				$result                   = saleOrderClass::isTax($field['num'] ?: $mx['num'], $field['price'] ?: $mx['price'], $field['rate'] ?: $mx['rate']);
				$field['taxMoney']        = $result['taxMoney'];
				$field['moneyWithOutTax'] = $result['moneyWithTax'];
				$field['money']           = $this->post('money') ?: $result['money'];
			}
			$warn = static::update([
				'table' => self::tableMx,
				'field' => $field,
				'where' => $where,
			], false);
			if ($warn == '更新成功') {
				$json['msg']  = $warn;
				$json['warn'] = 2;
			} else {
				$json['warn'] = $warn;
			}
		}
		return json_encode($json, 320);
	}


	// 操作中转
	public function operate()
	{
		$act    = $this->post('act') ?? '';
		$pwd    = false; // 需要密码
		$form   = $power = '';
		$append = [];
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'isDelete';
				$form     = self::page . 'OperateForm,listForm,contractForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'append'   => $append,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	// 确认删除信息
	public function isDelete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除" . self::title . "的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 判断field
			$fieldKey   = 'state';
			$fieldVlaue = '草稿';

			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if ($info['id']) {
					if ($info[$fieldKey] !== $fieldVlaue) {
						$text .= self::title . "【{$info['id']}】非{$fieldVlaue}状态，无法删除<br>";
						continue;
					}
					// 删除相关 附件
					$result = $this->sqlFind("SELECT id, src FROM `file` WHERE targetId = '{$info['id']}' ");
					foreach ($result as $attachFile) {
						delete([
							'table' => 'file',
							'where' => " id = '{$attachFile['id']}'",
						]);
						fileDelete($attachFile['src']);
					}

					delete([
						"table" => self::tableMx,
						"where" => " orderId = '$id' ",
					]);
					// 删除表
					delete([
						"table" => self::table,
						"where" => $where,
					]);
					//添加记录
					$text .= "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . "，名称【{$info['name']}】" . '<br>';
					$x++;
				}
			}

			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "删除了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}

		resp:
		return json_encode($json, 320);
	}
}
